package com.niu.edu;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.StringTokenizer;


public class App {
    // Map处理类，从Mapper派生
    public static class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        // 创建一个可写的整数对象，记录word的数量
        private final static IntWritable one = new IntWritable(1);
        // 创建一个Text对象，保存Word的值，作为输出数据的key
        private Text word = new Text();

        // map方法，实现map处理的地方
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 由单词内容创建一个Tokenizer，用于将value中的各Word分割出来，value的内容是一行文本
            StringTokenizer itr = new StringTokenizer(value.toString(),",");
            // 分割出各word
            while (itr.hasMoreTokens()) {
                // 将分割出的word的内容设置给字段word
                word.set(itr.nextToken());
                // 形成一对key-value，保存下来
                context.write(word, one);
            }
        }
    }

    public static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values, Context context)
                throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //创建Hadoop配置对象，使用默认配置
        Configuration conf = new Configuration();
        //创建一个MR作业，取名叫做word count，名字可用于管理作业
        Job job = Job.getInstance(conf, "word count");
        //告诉job可以跟据App这个类的元数据信息找到MR的jar文件
        job.setJarByClass(App.class);
        //将Mapper类加入job
        job.setMapperClass(MyMapper.class);
        //将Reducer类设置为合并器，在Mapper端执行Reducer的逻辑，减少输出数据
        job.setCombinerClass(MyReducer.class);
        //将Reducer类加入job
        job.setReducerClass(MyReducer.class);
        //设置MR最终输出的数据的Key类型
        job.setOutputKeyClass(Text.class);
        //设置MR最终输出的数据的Value类型
        job.setOutputValueClass(IntWritable.class);
        //设置Reducer数量
        job.setNumReduceTasks(2);
        //设置输入数据从哪个目录正的文件中读
        FileInputFormat.addInputPath(job, new Path(args[0]));
        //设置输出数据存放的文件在哪个目录下
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        //执行job并等待其结束，然后程序退出
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
